package com.huawei.petapp2.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.collection.ArrayMap;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseViewHolder;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.petapp2.R;
import com.huawei.petapp2.activity.widget.BaseActivity;
import com.huawei.petapp2.adapter.ShopBannerAdapter;
import com.huawei.petapp2.adapter.ViewPagerAdapter;
import com.huawei.petapp2.call.CartCountBeanback;
import com.huawei.petapp2.call.ShoppingCartVoCallback;
import com.huawei.petapp2.cart.DingdanActivity;
import com.huawei.petapp2.constant.HttpAddress;
import com.huawei.petapp2.constant.HttpUrl;
import com.huawei.petapp2.entity.CartCount;
import com.huawei.petapp2.entity.OrderInfos;
import com.huawei.petapp2.entity.Product;
import com.huawei.petapp2.entity.ProductVo;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.entity.ShopDetailBean;
import com.huawei.petapp2.entity.ShoppingCartVo;
import com.huawei.petapp2.entity.Shoppingcart;
import com.huawei.petapp2.entity.Storeitem;
import com.huawei.petapp2.entity.VideoMultyItem;
import com.huawei.petapp2.fragment.FMBadyDetail;
import com.huawei.petapp2.fragment.FMCommonList;
import com.huawei.petapp2.fragment.FMProductCase;
import com.huawei.petapp2.impl.UserImpl;
import com.huawei.petapp2.network.core.ResponseEntity;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.ParseUtils;
import com.huawei.petapp2.utils.PreferenceHelper;
import com.huawei.petapp2.utils.ScreenUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GoodDatailActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.shop_tablayout)
    TabLayout shopTablayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.shop_title_tv)
    TextView shopTitleTv;
    @BindView(R.id.shop_name_tv)
    TextView shopNameTv;
    @BindView(R.id.shop_price_tv)
    TextView shopPriceTv;
    @BindView(R.id.shop_vip_price_tv)
    TextView shopVipPriceTv;
    @BindView(R.id.shop_specif_tv)
    TextView shopSpecifTv;
    @BindView(R.id.sales_volume_tv)
    TextView salesVolumeTv;
    @BindView(R.id.coupon_tv)
    TextView couponTv;
    @BindView(R.id.coupon_content_tv)
    TextView couponContentTv;
    @BindView(R.id.coupon_next_iv)
    ImageView couponNextIv;
    @BindView(R.id.coupon_rl)
    RelativeLayout couponRl;
    @BindView(R.id.promotions_tv)
    TextView promotionsTv;
    @BindView(R.id.promotions_content_tv)
    TextView promotionsContentTv;
    @BindView(R.id.promotions_next_iv)
    ImageView promotionsNextIv;
    @BindView(R.id.promotions_rl)
    RelativeLayout promotionsRl;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.cart_tv)
    TextView cartTv;
    @BindView(R.id.service_tv)
    TextView serviceTv;
    @BindView(R.id.collection_tv)
    TextView collectionTv;
    @BindView(R.id.ll_head)
    LinearLayout llHead;
    @BindView(R.id.add_cart_btn)
    Button addCartBtn;
    @BindView(R.id.buy_now_btn)
    Button buyNowBtn;
    @BindView(R.id.al_shop_detail)
    AppBarLayout alShopDetail;
    @BindView(R.id.coll_toolbar_layout)
    CollapsingToolbarLayout collToolbarLayout;
    @BindView(R.id.content_cl)
    ConstraintLayout contentCl;
    @BindView(R.id.tv_home_statusbar)
    TextView tvHomeStatusbar;
    @BindView(R.id.nsv_good)
    NestedScrollView nsvGood;
    @BindView(R.id.ll_cart)
    LinearLayout llCart;
    CoordinatorLayout clGood;
    @BindView(R.id.tv_cart_count)
    TextView tvCartCount;
    @BindView(R.id.tv_take_name)
    TextView tvTakeName;
    @BindView(R.id.tv_year)
    TextView tvYear;
    @BindView(R.id.tv_mouth)
    TextView tvMouth;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.rl_take)
    RelativeLayout rlTake;

    //淘宝banner
    @BindView(R.id.shop_banner)
    RecyclerView headBanner;
    @BindView(R.id.banner_num)
    TextView bannerNum;
    private LinearLayoutManager mLayoutManager;
    private ShopBannerAdapter mShopBannerAdapter;
    private PagerSnapHelper mSnapHelper;

    int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
    String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));

    private ArrayList<Fragment> list;
    private Shoppingcart shoppingcarts = new Shoppingcart();

    private Shoppingcart simpleGoods;
    private ShoppingCartVo shoppingCartVo;

    private int mAlpha;
    private Shoppingcart shoppingcart=new Shoppingcart();
    private int goodCount;
    private boolean isBottom;
    private boolean isCollect = false;
    private View view;

    private AlertDialog addDialog;

    private ShopDetailBean detailModel;

    private ProductVo productVo;

    private CartCount cartCount;
    String cid;
    final private static Gson gson=new GsonBuilder().serializeNulls().create();
   // Storeitem storeitem;

    private FMCommonList fmCommonList = new FMCommonList();
    private FMProductCase fmProductCase = new FMProductCase();
    private FMBadyDetail fmBadyDetail = new FMBadyDetail();

    private static final String EXTRA_GOODS_ID = "EXTRA_GOODS_ID";

    public static Intent getStartIntent(Context context, int goodsId) {
        Intent intent = new Intent(context, GoodDatailActivity.class);
        intent.putExtra(EXTRA_GOODS_ID,String.valueOf(goodsId));
        return intent;
    }

    protected int getLayoutId() {
        return R.layout.activity_good_detial;
    }


    @Override
    protected int setLayoutId() {
        return R.layout.activity_good_detial;
    }




    @SuppressLint("WrongViewCast")
    @Override
    public void initView() throws Exception {
        //传输过来的
        cid=getIntent().getStringExtra(EXTRA_GOODS_ID);
        OkHttpClient client = new OkHttpClient();
        toolbar=findViewById(R.id.toolbar);

        shopTablayout=findViewById(R.id.shop_tablayout);
        viewPager=findViewById(R.id.viewPager);
        shopTitleTv=findViewById(R.id.shop_title_tv);
        shopNameTv=findViewById(R.id.shop_name_tv);
        shopPriceTv=findViewById(R.id.shop_price_tv);
        shopVipPriceTv=findViewById(R.id.shop_vip_price_tv);
        shopSpecifTv=findViewById(R.id.shop_specif_tv);
        salesVolumeTv=findViewById(R.id.sales_volume_tv);
        couponTv=findViewById(R.id.coupon_tv);
        couponContentTv=findViewById(R.id.coupon_content_tv);
        couponNextIv=findViewById(R.id.coupon_next_iv);
        couponRl=findViewById(R.id.coupon_rl);
        promotionsTv=findViewById(R.id.promotions_tv);
        promotionsContentTv=findViewById(R.id.promotions_content_tv);
        promotionsNextIv=findViewById(R.id.promotions_next_iv);
        promotionsRl=findViewById(R.id.promotions_rl);
        toolbarTitle=findViewById(R.id.toolbar_title);
        ivTitleRight=findViewById(R.id.iv_title_right);
        cartTv=findViewById(R.id.cart_tv);
        serviceTv=findViewById(R.id.service_tv);
        collectionTv=findViewById(R.id.collection_tv);
        llHead=findViewById(R.id.ll_head);
        addCartBtn=findViewById(R.id.add_cart_btn);
        buyNowBtn=findViewById(R.id.buy_now_btn);
        alShopDetail=findViewById(R.id.al_shop_detail);
        collToolbarLayout=findViewById(R.id.coll_toolbar_layout);
        contentCl=findViewById(R.id.content_cl);
        tvHomeStatusbar=findViewById(R.id.tv_home_statusbar);
        nsvGood=findViewById(R.id.nsv_good);
        llCart=findViewById(R.id.ll_cart);
        tvCartCount=findViewById(R.id.tv_cart_count);
        tvTakeName=findViewById(R.id.tv_take_name);
        tvYear=findViewById(R.id.tv_year);
        tvMouth=findViewById(R.id.tv_mouth);
        tvDay=findViewById(R.id.tv_day);
        rlTake=findViewById(R.id.rl_take);

        viewPager.setOffscreenPageLimit(3);
        setSupportActionBar(toolbar);
        setSupportActionBar(toolbar);

        //淘宝banner初始化
        headBanner=findViewById(R.id.shop_banner);
        bannerNum=findViewById(R.id.banner_num);
        initData();
        initToolBar();
        initScrollView();
        initBanner();
    }

    public void onTest(Storeitem storeitem)
    {

    }


    public Product call(String cid) throws Exception {
        final Product[] goods = new Product[1];
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(HttpUrl.getBaseUrl()+"/product/detail-info/"+cid)//请求的url
                .addHeader("Token",token)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    System.out.println("新的商品列表请求OnintView11"+result+"\n");
                    goods[0] = DateUtil.getEntity(result, Product.class);
                    System.out.println("异步线程中的数据11"+goods[0]);
                }
            }
        });
        System.out.println("异步线程中的数据11"+goods[0]);
        return goods[0];
    }



    @Override
    public void initData() throws Exception {
        int userId= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));

        Result result =DateUtil.selectList(
                HttpAddress.get(HttpAddress.detailProduct(),"detail-info", Integer.parseInt(cid)));
         System.out.println("dayingduixiang的rusult" +result.getResult());

        productVo=DateUtil.getEntity(result, ProductVo.class);

        System.out.println("dayingduixiang"+productVo.toString());
        //System.out.println("在intDate中的数据");
        System.out.println("商品详情中的商品名称"+productVo.getProduct().getProductName());
        System.out.println("商品详情中的商品描述"+productVo.getProduct().getContent());
        toolbar.setTitle(productVo.getProduct().getProductName());
        shopTitleTv.setText(productVo.getProduct().getProductName());
        shopNameTv.setText(productVo.getProduct().getContent());
        upDateCartNumber(Integer.valueOf(productVo.getProduct().getProductId()));
        String marketPrice="";
        String sovePrice="";


        if(productVo.getProductSkus().size()>0)
        {
            marketPrice=Integer.toString(productVo.getProductSkus().get(0).getOriginalPrice());
            sovePrice=Integer.toString(productVo.getProductSkus().get(0).getSellPrice());
        }
        shopPriceTv.setText(marketPrice);
        shopVipPriceTv.setText(String.valueOf(sovePrice));
        viewPager.setOffscreenPageLimit(3);
        setSupportActionBar(toolbar);
        setSupportActionBar(toolbar);
        viewPager.setOffscreenPageLimit(3);
        setSupportActionBar(toolbar);
        initToolBar();
        initScrollView();
        initBanner();
        initTabLayout();
    }

    @Override
    public void initEvent() {

    }


    private void initTabLayout() {
        list = new ArrayList<Fragment>();
        Bundle bundle = new Bundle();
        bundle.putSerializable("storeitem", productVo);
        fmBadyDetail.setArguments(bundle);
        fmCommonList.setArguments(bundle);
        fmProductCase.setArguments(bundle);
        list.add(fmBadyDetail);//宝贝详情
        list.add(fmProductCase);//产品案例
        list.add(fmCommonList);//商品评价
        ViewPagerAdapter vpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(vpAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener
                (shopTablayout));
        shopTablayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener
                (viewPager));
    }
    private void initBanner() {
        List<VideoMultyItem> mList = new ArrayList<>();
        //添加一个视频VideoMultyItem中三个参数，第一个参数是视频的地址，第二个参数1 是视频  2  是商品，第三个参数为图片地址（视频类型时用作视频封面）
        mList.add(new VideoMultyItem("http://vjs.zencdn.net/v/oceans.mp4", 1, "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimages.669pic.com%2Felement_pic%2F55%2F44%2F38%2F7%2F07097c64a940a7c1b669345f1c6360ca.jpg&refer=http%3A%2F%2Fimages.669pic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630490770&t=c8a62639eafd4fe4f26a545f28ab853d"));
        for (int i = 0; i < 5; i++) {
            mList.add(new VideoMultyItem(null, 2, "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimages.669pic.com%2Felement_pic%2F55%2F44%2F38%2F7%2F07097c64a940a7c1b669345f1c6360ca.jpg&refer=http%3A%2F%2Fimages.669pic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630490770&t=c8a62639eafd4fe4f26a545f28ab853d"));
        }
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        headBanner.setLayoutManager(mLayoutManager);
        mShopBannerAdapter = new ShopBannerAdapter(mList);
        mSnapHelper = new PagerSnapHelper();
        headBanner.setOnFlingListener(null);
        mSnapHelper.attachToRecyclerView(headBanner);
        headBanner.setAdapter(mShopBannerAdapter);
        bannerNum.setText("1/" + mList.size());
        headBanner.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) headBanner.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                bannerNum.setText((position + 1) + "/" + mList.size());
            }
        });
        headBanner.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        //停止滚动
                        autoPlay(recyclerView);
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        //拖动
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        //惯性滑动
                        Jzvd.releaseAllVideos();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void autoPlay(RecyclerView recyclerView) {
        View view = mSnapHelper.findSnapView(mLayoutManager);

        if (view != null) {
            if (view instanceof RelativeLayout) {
                Jzvd.releaseAllVideos();
            } else {
                BaseViewHolder viewHolder = (BaseViewHolder) recyclerView.getChildViewHolder(view);

                if (viewHolder != null) {
                    JzvdStd myVideoPlayer = viewHolder.getView(R.id.player);
                    myVideoPlayer.startVideo();
                }
            }
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        JzvdStd.releaseAllVideos();
    }

    @Override
    protected void onBusinessResponse(String apiPath, boolean success, ResponseEntity rsp) {

    }

    private void initScrollView() {
        //监听AppBarLayout滑动状态
        alShopDetail.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {

            if (appBarLayout.getTotalScrollRange() == -verticalOffset) {
                if (isBottom) {
                } else {
                    isBottom = true;
                }
            } else {
                isBottom = false;
            }
            int minHeight = 50;
            if (headBanner != null && headBanner.getMeasuredHeight() != 0) {
                int maxHeight = headBanner.getMeasuredHeight() / 2;
                if (maxHeight == 0) {
                    maxHeight = 255;
                }
                if (Math.abs(verticalOffset) <= minHeight) {
                    mAlpha = 0;
                } else if (Math.abs(verticalOffset) > maxHeight) {
                    mAlpha = 255;
                } else {
                    mAlpha = (Math.abs(verticalOffset) - minHeight) * 200 / (maxHeight - minHeight);
                }
                if (mAlpha <= 0) {
                    llHead.setBackgroundColor(Color.argb(0, 255, 255, 255));
                } else if (mAlpha >= 255) {
                    llHead.setBackgroundColor(Color.argb(mAlpha, 255, 255, 255));
                } else {
                    llHead.setBackgroundColor(Color.argb(mAlpha, 255, 255, 255));
                }
            }
        });
    }




    private void initToolBar() {

    }




    private void upDateCartNumber(int productId) {
        getProductCount(this.view,productId);
    }

    /**
     * 商品是否已收藏
     *
     * @param goods_id
     */
    private void getIsCollect(String goods_id) {
        ArrayMap<String, String> map = new ArrayMap<>();
        map.put("user_id", UserImpl.getUserId());
        map.put("ele_id", goods_id);
        map.put("collert_id", "0");
        map.put("type", "1");

    }


    @OnClick({R.id.coupon_rl, R.id.promotions_rl, R.id.cart_tv, R.id.service_tv, R.id.collection_tv, R.id.add_cart_btn, R.id.buy_now_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.coupon_rl:
                //showCouponDialog();//领优惠券
                break;
            case R.id.promotions_rl:
                //showPromotionsDialog();//促销活动
                break;
            case R.id.cart_tv:
                break;
            case R.id.add_cart_btn://加入购物车
                showAddCartDialog(1);
                break;
            case R.id.buy_now_btn://立即购买
                showAddCartDialog(2);
                break;
            case R.id.service_tv://客服
                break;
            case R.id.collection_tv://收藏商品
                if (isCollect) {
                    //请求取消收藏接口
                } else {
                    //获取收藏列表接口
                }
                break;
        }
    }


    /**
     * 加入购物车
     * 由于没有接口,所以数量缓存有问题,小伙伴们看效果就好了
     */
    @SuppressLint("SetTextI18n")
    private void showAddCartDialog(final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
        addDialog = builder.show();
        LayoutInflater inflater = LayoutInflater.from(this);
        this.view = inflater.inflate(R.layout.dialog_add_cart, null);
        WindowManager.LayoutParams params = addDialog.getWindow().getAttributes();
        params.width = ScreenUtil.getScreenWidth(this);
        //主动弹出输入法键盘
        addDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        addDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        addDialog.getWindow().setGravity(Gravity.BOTTOM);
        addDialog.getWindow().setAttributes(params);
        addDialog.getWindow().setContentView(view);
        addDialog.setCanceledOnTouchOutside(true);
        addDialog.setCancelable(true);
        final TextView clearTv = view.findViewById(R.id.clear_tv);
        final ImageView addBtn = view.findViewById(R.id.add_count_btn);
        final ImageView minusBtn = view.findViewById(R.id.minus_count_btn);
        final Button finishBtn = view.findViewById(R.id.finish_btn);
        final EditText cartCount = view.findViewById(R.id.edit_count);
        final RelativeLayout rlAdd = view.findViewById(R.id.rl_add);
        cartCount.setSelection(getTV(cartCount).length());
        finishBtn.setOnClickListener(v -> addDialog.dismiss());
        final int count = ParseUtils.parseInt(cartCount.getText().toString());
        if (count <= 1) {
            cartCount.setClickable(false);
            minusBtn.setBackgroundResource(R.mipmap.minus_grey);
        } else {
            minusBtn.setBackgroundResource(R.mipmap.minus);
        }
        minusBtn.setOnClickListener(v -> {
            int count1 = ParseUtils.parseInt(cartCount.getText().toString());
            if (count1 > 1) {
                count1--;
                cartCount.setText(count1 + "");
                cartCount.setSelection(cartCount.length());
                if (count1 == 1) {
                    cartCount.setClickable(false);
                    minusBtn.setBackgroundResource(R.mipmap.minus_grey);
                }
            } else {
                cartCount.setClickable(false);
                cartCount.setSelection(cartCount.length());
                minusBtn.setBackgroundResource(R.mipmap.minus_grey);
            }
        });
        addBtn.setOnClickListener(v -> {
            int count12 = ParseUtils.parseInt(cartCount.getText().toString());
            count12++;
            cartCount.setText(count12 + "");
            cartCount.setClickable(true);
            cartCount.setSelection(cartCount.length());
            minusBtn.setBackgroundResource(R.mipmap.minus);
        });
        clearTv.setOnClickListener(v -> {
            cartCount.setText(count + "");
            cartCount.setSelection(cartCount.length());
        });
        cartCount.setFocusableInTouchMode(true);

        finishBtn.setOnClickListener(v -> {
            addDialog.dismiss();
        /*    if (detailModel == null || ParseUtils.parseInt(detailModel.getGoods_number()) <= 0) {
                showToast("商品已售罄");
                return;
            }
*/          int userId= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
            String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));
            int count13 = ParseUtils.parseInt(getTV(cartCount));
            if (count13 <= 0) {
                showToast("请输入正确的数量");
                return;
            }

            if (type == 1) {
                int cartNum=ParseUtils.parseInt(getTV(cartCount));
                String productId=productVo.getProduct().getProductId();
                String skuId=productVo.getProductSkus().get(0).getSkuId();
                int storid=productVo.getProduct().getStoreid();
                String skuContent=productVo.getProductSkus().get(0).getSkuName();
                int productPrice=productVo.getProductSkus().get(0).getSellPrice();

                getShoppingcart(this.view,1,Integer.valueOf(productId).intValue(),productPrice,Integer.valueOf(skuId).intValue(),skuContent);
                OkHttpClient client = new OkHttpClient();
                Request request1 = new Request.Builder()//当前用户加入购物车
                        .url(HttpUrl.getBaseUrl()+"/shopcart/add/"+cartNum+"/"+userId+"/"+productId+"/"+productPrice+"/"+storid+"/"+skuId+"/"+skuContent)
                        .addHeader("Token",token)
                        .build();

                client.newCall(request1).enqueue(new Callback() {

                    private OrderInfos orderInfos;

                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Looper.prepare();//增加部分
                        if(response.code() >= 200 && response.code() < 300) {
                            String results = response.body().string();
                            Result result=gson.fromJson(results,Result.class);
                            System.out.println("加入购物车回调"+results);
                        }
                        Looper.loop();//增加部分
                    }
                });




                //  CartImpl.addCart(detailModel, ParseUtils.parseInt(getTV(cartCount)));
                upDateCartNumber(Integer.valueOf(productId));
                showToast("加入成功");
            } else {
                if (productVo != null) {
                    List<CartCount> computeModels = new ArrayList<>();
                    CartCount m = new CartCount();
                    m.setProductId(Integer.valueOf(productVo.getProduct().getProductId()));
                    goodCount = ParseUtils.parseInt(getTV(cartCount));
                    m.setCartNum(goodCount);
                    computeModels.add(m);

                    String productId=productVo.getProduct().getProductId();
                    String skuId=productVo.getProductSkus().get(0).getSkuId();
                    int storid=productVo.getProduct().getStoreid();
                    String skuContent=productVo.getProductSkus().get(0).getSkuName();
                    int productPrice=productVo.getProductSkus().get(0).getSellPrice();

                  //  getShoppingcart(this.view,1,Integer.valueOf(productId).intValue(),productPrice,Integer.valueOf(skuId).intValue(),skuContent);
                    Intent intent=new Intent();
                    intent.putExtra("money",productPrice);
                    intent.putExtra("state","single");
                    intent.setClass(getApplicationContext(), DingdanActivity.class);
                    startActivity(intent);
                    //  CartImpl.addCart(detailModel, ParseUtils.parseInt(getTV(cartCount)));
                    upDateCartNumber(Integer.valueOf(productId));
                    showToast("加入成功");
                }
            }
        });
        rlAdd.setOnClickListener(v -> addDialog.dismiss());
    }

    public Shoppingcart getShoppingcart(View view,int cartNum, int productId,int productPrice,
                                        int skuId,String skuProps)
    {
        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=format.format(date);
        int userId= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));

        String url = HttpUrl.getBaseUrl()+"/shopcart/add/"+cartNum+"/"+userId+"/"+productId+"/"+productPrice+"/"+skuId+"/"+skuProps;
        OkHttpUtils//
                .get()
                .url(url)//
//                .params(params)//
                .addHeader("Token",token)
                .build()//
                .execute(new ShoppingCartVoCallback()//
                {


                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(ShoppingCartVo response, int id) {
                        int count=Integer.valueOf(response.getCartNum()).intValue();
                        shoppingCartVo =response;
                        System.out.println("当前购物车数量"+count);
                       // int count = CartImpl.getCartSize();
                    }

                });
        return simpleGoods;

    }



    public CartCount getProductCount(View view,  int productId)
    {
        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=format.format(date);
        int userId= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));

        String url = HttpUrl.getBaseUrl()+"/shopcart/listbypid/"+userId+"/"+productId;
        OkHttpUtils//
                .get()
                .url(url)//
//                .params(params)//
                .addHeader("Token",token)
                .build()//
                .execute(new CartCountBeanback()//
                {

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(CartCount response, int id) {
                        int count=Integer.valueOf(response.getCartNum()).intValue();
                        cartCount =response;
                        System.out.println("当前购物车数量"+count);
                        if (tvCartCount == null) {
                            return;
                        }
                        if (count == 0) {
                            tvCartCount.setVisibility(View.GONE);
                        } else {
                            tvCartCount.setVisibility(View.VISIBLE);
                            tvCartCount.setText(count > 99 ? "99+" : count + "");
                        }
                    }

                });
        return cartCount;

    }
}